// pages/addProject/addProject.js
import { createResumeService } from "../../api/resume";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    myProjectInfo:"",
    myProjectContribution:"",
    myProjectResult:"",
    Initiator:"",
    Position:"",
    myDirection:"落地",
    joinDate: '2010-00-00',
    stopDate: '2010-00-00',
    todayDate: '',
    isSubmitting: false
  },

  myProjectInfo(e){
    this.setData({
      myProjectInfo: e.detail.value,
    });
  },
  myProjectContribution(e){
    this.setData({
      myProjectContribution: e.detail.value,
    });
  },
  myProjectResult(e){
    this.setData({
      myProjectResult: e.detail.value,
    });
  },
  Initiator(e){
    this.setData({
      Initiator: e.detail.value,
    });
  },
  Position(e){
    this.setData({
      Position: e.detail.value,
    });
  },


  myDirection(e) {
    const myDirection = e.currentTarget.dataset.myDirection || e.target.dataset.mydirection;
    if (myDirection) {
      this.setData({
        myDirection: myDirection,
      });
      console.log(this.data.myDirection);
    } else {
      console.error('未能获取到项目方向数据');
    }
  },

  joinDate(e){
    this.setData({
      joinDate: e.detail.value
    })
    console.log(this.data.joinDate)
  },
  stopDate(e){
    this.setData({
      stopDate: e.detail.value
    })
    console.log(this.data.stopDate)
  },
  nostopDate(){
    this.setData({
      stopDate: "至今"
    })
  },

  // 数据验证函数
  validateForm() {
    const {
      myProjectInfo,
      myProjectContribution,
      Initiator,
      Position,
      joinDate
    } = this.data;

    if (!myProjectInfo.trim()) {
      wx.showToast({
        title: "请输入项目简要信息",
        icon: "none",
      });
      return false;
    }

    if (!myProjectContribution.trim()) {
      wx.showToast({
        title: "请输入项目中你的贡献",
        icon: "none",
      });
      return false;
    }

    if (!Initiator.trim()) {
      wx.showToast({
        title: "请输入发起方",
        icon: "none",
      });
      return false;
    }

    if (!Position.trim()) {
      wx.showToast({
        title: "请输入你的角色",
        icon: "none",
      });
      return false;
    }

    if (!joinDate || joinDate === '2010-00-00') {
      wx.showToast({
        title: "请选择加入时间",
        icon: "none",
      });
      return false;
    }

    return true;
  },

  // 转换数据格式以匹配后端API
  formatDataForAPI() {
    // 方向转换
    let projectBelief = "1";
    if (this.data.myDirection === "落地") {
      projectBelief = "1";
    } else if (this.data.myDirection === "获奖") {
      projectBelief = "2";
    } else if (this.data.myDirection === "学习") {
      projectBelief = "3";
    }

    // 构建请求数据对象
    const requestData = {
      joinTime: this.data.joinDate,
      projectInfo: this.data.myProjectInfo,
      projectResult: this.data.myProjectResult,
      role: this.data.Position,
      projectBelief: projectBelief,
      projectContribution: this.data.myProjectContribution,
      initiator: this.data.Initiator
    };

    // 只有当结束日期不是"至今"时才添加endTime字段
    if (this.data.stopDate !== "至今" && this.data.stopDate !== '2010-00-00') {
      requestData.endTime = this.data.stopDate;
    }

    return requestData;
  },

  confirmAdd() {
    // 防止重复提交
    if (this.data.isSubmitting) {
      return;
    }

    // 验证表单
    if (!this.validateForm()) {
      return;
    }

    this.setData({
      isSubmitting: true,
    });

    // 格式化数据
    const requestData = this.formatDataForAPI();
    console.log("提交数据：", requestData);
    // 添加日志输出，显示所有传递到后端的参数
    console.log("发送到后端的简历项目数据:", requestData);
    
    // 显示加载提示
    wx.showLoading({
      title: "添加中...",
      mask: true,
    });

    // 发送请求到后端
    createResumeService(requestData)
      .then((res) => {
        wx.hideLoading();

        if (res.code === 200) {
          // wx.showToast({
          //   title: "添加成功",
          //   icon: "success",
          //   duration: 2000,
          //   success: () => {
          //     setTimeout(() => {
          //       wx.navigateBack();
          //     }, 1500);
          //   }
          // });
          // 使用 wx.showModal 替代 wx.showToast，因为 modal 不会被页面跳转中断
          wx.showModal({
            title: '添加成功',
            content: '项目已成功添加到您的简历中',
            showCancel: false,
            confirmText: '确定',
            success: () => {
              // 点击确定后立即返回
              wx.navigateBack();
            }
          });
        } else {
          wx.showToast({
            title: res.message || "添加失败",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("添加失败：", err);
        wx.showToast({
          title: "网络异常，请重试",
          icon: "none",
        });
      })
      .finally(() => {
        this.setData({
          isSubmitting: false,
        });
      });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 获取当前日期并设置为结束日期默认值
    const today = this.formatDate(new Date());
    this.setData({
      todayDate: today
    });
  },

  /**
   * 格式化日期为 YYYY-MM-DD 格式
   */
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

})